﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections;


/// <summary>
/// Summary description for Str
/// </summary>
namespace Utils.Str
{
public class Formatter
{

		public static void Sanitize(ref string s , string quoteChar ) 
		{
				s = quoteChar + s + quoteChar ;
		} //eof method Sinitize (ref string s , char quoteChar ) 

		public static string Sanitize ( object s , string quoteChar )
		{
				string str = s.ToString ();
				str = quoteChar + s + quoteChar;
				return str;
		} //eof method Sanitize ( object s , char quoteChar )


		public static string StripQuotes ( string s , string quoteChar )
		{
				return s.Replace ( quoteChar , String.Empty );
		} //eof method SripQotes ( string s , string quoteChar) 


		public static string FromObjToShortDateString ( object filledValue )
		{
				string strTime =  System.Convert.ToString ( filledValue ).Trim ();
				//debugOk Utils.Debugger.WriteIf ( "The time string is " + strTime );
				//Old Data Format
				CultureInfo	culture = Utils.Str.Formatter.GetCultureInfoToUse ();
				DateTime dtDate = DateTime.Parse ( strTime , culture );
				//debugOk Utils.Debugger.WriteIf ( "My dtDate.ToString() is " + dtDate.ToShortDateString () );
				//New Data Format
				return dtDate.ToShortDateString ();
				//debugOk Utils.Debugger.WriteIf ( "The smalldate time is dd.mm.yyyy" + dtDate.ToString ( "dd.mm.yyyy" ) );
		} //eof method FromObjToShortDateString ( object o )


		public static string FromObjToLongDateString ( object filledValue )
		{
				//TODO: REPLACE THOSE HARDCODED DATEFORMATS WITH CUSTOMER SETTINGS
				string strTime =  System.Convert.ToString ( filledValue ).Trim ();
				//debugOk Utils.Debugger.WriteIf ( "The time string is " + strTime );
				//Old Data Format
				CultureInfo	culture = Utils.Str.Formatter.GetCultureInfoToUse ();
				DateTime dtDate = DateTime.Parse ( strTime , culture );
				//debugOk Utils.Debugger.WriteIf ( "My dtDate.ToLongTimeString() is " + dtDate.ToLongTimeString () );
				//New Data Format
				return  dtDate.ToLongTimeString ();
				//debugOk Utils.Debugger.WriteIf ( "The datetime time " + dtDate.ToLongTimeString () );
		} //eof method  FromObjToLongDateString ( object filledValue )


		public static string FindAndReplace (string s , string findRegex , string replaceRegex)
		{ 
		    Regex Remover = new Regex ( @"^" + findRegex + "$",
        RegexOptions.IgnoreCase | RegexOptions.Compiled );
				 return Remover.Replace ( s , replaceRegex );
		} //eof method FindAndReplace ()


		public static string ConvertSqlToDate ( string s , string columnName )
		{
				//debugOk Utils.Debugger.WriteIf ( "My s is :" + s );
				//debugOk Utils.Debugger.WriteIf ( "My columnName is:" + columnName );

				s = s.ToLower ();
				columnName = columnName.ToLower ();
				SortedList sl = new SortedList ();

				sl.Add ( "datediff(dd, " + columnName + " , getdate()) = 0 and " , "today" );
				sl.Add ( "datediff(dd, " + columnName + " , getdate()) = 1 and " , "yesterday" );
				sl.Add ( "datediff(dd, " + columnName + " , getdate()) < 7 and " , "week" );
				sl.Add ( "datediff(dd, " + columnName + " , getdate()) < 30 and " , "month" );


				for (int i = 0; i < sl.Count; i++)
				{
						if (s.Equals ( sl.GetKey ( i ) ))
						{
								return Convert.ToString ( sl.GetByIndex ( i ) );
						}
				} //eof for


				Regex re = new Regex ( @"^datediff(dd, " + columnName +  " , getdate()) = (\\d){1,9} and $" , RegexOptions.IgnoreCase );
				Match m = re.Match ( s );

				if (m.Success)
				{
						Regex Remover = new Regex ( @"^datediff(dd," + columnName+ " , getdate()) (\\d){1,9} and $" ,
						RegexOptions.IgnoreCase | RegexOptions.Compiled );
						string news = Remover.Replace ( s , "last $1 days" );
						return news;
				}

				return s;								//this means that in the textbox no sql codes have been input


		} //eof method ConvertSqlToDate


		public static string ConvertDateToSql ( string s , string columnName )
		{		//trop_convertDateToSql
				s = s.ToLower ();
				columnName = columnName.ToLower ();

				SortedList sl = new SortedList ();
				sl.Add ( "today" , "datediff(dd, " + columnName + " , getdate()) = 0 and " );
				sl.Add ( "yesterday" , "datediff(dd, " + columnName + " , getdate()) = 1 and " );
				sl.Add ( "week" , "datediff(dd, " + columnName + " , getdate()) < 7 and " );
				sl.Add ( "month" , "datediff(dd, " + columnName + " , getdate()) < 30 and " );


				//comm - cycle trough the SortedList having the key -- values for today -- dfii.. code Sql
				for (int i = 0; i < sl.Count; i++)
				{
						if (s.Equals ( sl.GetKey ( i ) ))
						{
								return Convert.ToString ( sl.GetByIndex ( i ) );
						}
				} //eof for


				Regex re = new Regex ( @"^last (\d){1,9} days$" , RegexOptions.IgnoreCase );
				Match m = re.Match ( s );

				if (m.Success)
				{
						Regex Remover = new Regex ( @"^last (\d){1,9} days$" ,
						RegexOptions.IgnoreCase | RegexOptions.Compiled );
						string news = Remover.Replace ( s , "datediff(dd, " + columnName+ " , getdate()) < $1 and " );
						return news;
				}

				return s;								//this means that in the textbox no sql codes have been input

		} //eof method ConvertDateToSql ( ref string s ) 



		public static string getBaseDir ()
		{

			string absoluteUri = System.Web.HttpContext.Current.Request.Url.OriginalString;
			string pathAndQuery = System.Web.HttpContext.Current.Request.Url.PathAndQuery;

			string hostAndPort = absoluteUri.Substring ( 0, (absoluteUri.Length - pathAndQuery.Length) );
			string hostAndPortAndBaseDir = hostAndPort + System.Web.HttpContext.Current.Request.ApplicationPath + "/";


			//Utils.Debugger.WriteIf ( "baseDir is " + hostAndPortAndBaseDir );
			return hostAndPortAndBaseDir ;
			} //eof method getBaseDir 
	
		//Utils.Str.Formatter.FormatDecimalNumber  ( needsFormatting , ref filledValue ) 
		//deprecated TODO: REMOVE IF NOT USED
		public static string FormatDecimalNumber  ( bool flagNeedsFormatting , 
				ref string filledValue ) 
		{
				//TODO:APPLY CULTURE SPECIFIC COMMA AND DECIMAL DELIMITERS
				//E.G. pass CultureInfo specifig string 
				if (flagNeedsFormatting == false)
						return filledValue;

				else if (filledValue !=null && flagNeedsFormatting &&
						filledValue.Equals ( String.Empty ) == false && 
						filledValue.Equals ( " " ) == false)
				{
						CultureInfo cultureToUseInDisplay = Utils.Str.Formatter.GetCultureInfoToUse ();
						double doubleFilledValue = System.Convert.ToDouble ( filledValue , cultureToUseInDisplay );
						filledValue = String.Format ( cultureToUseInDisplay , "{0:N3}" , doubleFilledValue );
						return filledValue;
				} //eof if needs Formatting
				else
						return filledValue;
		
		} //eof method FormatDecimalNumber 


		//Utils.Str.Formatter.FormatDecimalNumber  ( needsFormatting , ref filledValue ) 
		public static bool FormatDecimalNumberAdv ( ref string msg , bool flagNeedsFormatting ,
				ref string filledValue )
		{
				//TODO:APPLY CULTURE SPECIFIC COMMA AND DECIMAL DELIMITERS
				//E.G. pass CultureInfo specifig string 
				double doubleFilledValue    ;

				if (flagNeedsFormatting == false)
						return true ;

				//if we need formatting handle all the empty number cases 
				switch ( filledValue )  {

						case null :
								return true ;
						case "":
								return true ; 
						case " " :
								return true ; 
						case "  " : 
								return true ; 
						} //eof 0switch

				//if we have some value check that it is double 
				try 
				{
						//comm - check if the number is correct according to display rules ( CurrentInfoToUse) 
						//comm - BUT save it according to Database rules -- e.g. DataBase culture 
						//Utils.Debugger.WriteIf ( "FormatDecimalNumberAdv - try inside " );
						CultureInfo cultureToUseInDisplay = Utils.Str.Formatter.GetCultureInfoToUse ();
						CultureInfo dataBaseCultureInUse = Utils.Str.Formatter.GetDataBaseCulture ();
						//comm -- convert to double according to the rules in the database 
						doubleFilledValue = System.Convert.ToDouble ( filledValue , dataBaseCultureInUse );
						//comm -- display the double according to the display rules 
						filledValue = String.Format ( cultureToUseInDisplay , "{0:N3}" , doubleFilledValue );
						//debugOk Utils.Debugger.WriteIf ( "After conversation in the TextBox the filledValue is " + filledValue );
						return true; 
				} 
				catch ( System.FormatException fe ) 
				{
						return true; 
				} //eof catch ( System.FormatException 

				catch ( System.OverflowException oe ) 
				{
						filledValue = System.Convert.ToString ( Double.MaxValue );
						msg = " The number passed from the database is too large for the application to handle it. " + 
								"Returning the biggest possible number. Report to advanced application support the following " + 
								"error: " + oe.Message;
						return false;
				} //eof System.OverflowException
		} //eof method FormatDecimalNumber 


		//Utils.Str.Formatter.FormatDecimalNumber  ( needsFormatting , ref filledValue ) 
		public static bool FormatDecimalNum ( ref string filledValue )
		{
			//TODO:APPLY CULTURE SPECIFIC COMMA AND DECIMAL DELIMITERS
			//E.G. pass CultureInfo specifig string 
			double doubleFilledValue;
			//if we have some value check that it is double 
			try
			{
				//comm - check if the number is correct according to display rules ( CurrentInfoToUse) 
				//comm - BUT save it according to Database rules -- e.g. DataBase culture 
				//Utils.Debugger.WriteIf ( "FormatDecimalNumberAdv - try inside " );
				CultureInfo cultureToUseInDisplay = Utils.Str.Formatter.GetCultureInfoToUse ( );
				CultureInfo dataBaseCultureInUse = Utils.Str.Formatter.GetDataBaseCulture ( );
				//comm -- convert to double according to the rules in the database 
				doubleFilledValue = System.Convert.ToDouble ( filledValue, dataBaseCultureInUse );
				//comm -- display the double according to the display rules 
				filledValue = String.Format ( cultureToUseInDisplay, "{0:N3}", doubleFilledValue );
				//debugOk Utils.Debugger.WriteIf ( "After conversation in the TextBox the filledValue is " + filledValue );
				return true ;
			}
			catch ( System.FormatException fe )
			{
				return false;
			} //eof catch ( System.FormatException 
			catch ( System.OverflowException oe )
			{
				filledValue = System.Convert.ToString ( Double.MaxValue );
				return false;
			} //eof System.OverflowException
		} //eof method FormatDecimalNumber 



		/// <summary>
		/// Defines the format the application should use for 
		/// </summary>
		/// <returns></returns>
		public static CultureInfo GetCultureInfoToUse ()
		{
				//todo: get passing from database
				CultureInfo cultureToUseInDisplay = new CultureInfo ( "fi-FI" );
				cultureToUseInDisplay.NumberFormat.CurrencyDecimalDigits = 3;
				cultureToUseInDisplay.NumberFormat.NumberDecimalDigits = 3;
				cultureToUseInDisplay.NumberFormat.NumberGroupSeparator = " ";
				cultureToUseInDisplay.NumberFormat.NumberDecimalSeparator = ".";
				return cultureToUseInDisplay; 
		}//eof method getCultureInfoToUse


		public static CultureInfo GetDataBaseCulture()
		{
				//todo: get passing from database
				CultureInfo cultureToUseInDataBase = new CultureInfo ( "fi-FI" );
				cultureToUseInDataBase.NumberFormat.CurrencyDecimalDigits = 3;
				cultureToUseInDataBase.NumberFormat.NumberDecimalDigits = 3;
				cultureToUseInDataBase.NumberFormat.NumberGroupSeparator = " ";
				cultureToUseInDataBase.NumberFormat.NumberDecimalSeparator = ",";
				return cultureToUseInDataBase;
		}//eof method getCultureInfoToUse


} // eof public class Formatter
} //eof namespace Utils.Str